package com.xiashitech.authservice.util;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.springframework.cglib.beans.BeanCopier;

public class BeanCopierUtil {
    private static final Table<Class, Class, BeanCopier> BEAN_COPIER_TABLE = HashBasedTable.create();

    public static <T, R> R copy(T t, Class<R> clazz) {
        BeanCopier beanCopier = BEAN_COPIER_TABLE.get(t.getClass(), clazz);
        if (beanCopier == null) {
            beanCopier = BeanCopier.create(t.getClass(), clazz, false);
            BEAN_COPIER_TABLE.put(t.getClass(), clazz, beanCopier);
        }
        try {
            R instance = clazz.newInstance();
            beanCopier.copy(t, instance, null);
            return instance;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
